<template>
  <div>
    <el-dialog
        @close="handleDialogClose"
      :title="headerTitle"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="460px"
    >
      <el-form
          ref="form"
          id="addTips"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="更改考勤班次" prop="workingScheduleId" v-if="formType == '1'">
          <el-select v-model="form.workingScheduleId" :loading="classesLoading" placeholder="请选择">
            <el-option v-for="(item,index) in classesList" :key="item.id"  :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- -=-=-=-=-= -->
        <template v-if="['2', '3'].includes(formType)">
          <el-row>
            <el-form-item label="名称" align="left" prop="name">
              <el-input v-model="form.name" align="left" placeholder="请输入"></el-input>
            </el-form-item>
          </el-row>
          <template v-if="formType == '3'">
            <el-button size="small" type="primary" class="newShift" @click="addClasses"
              >
              {{this.i18n.t('New classes')}}
              </el-button
            >
          <el-row>
          <el-form-item label="选择班次" prop="workingScheduleId">
            <el-select v-model="form.workingScheduleId" :loading="classesLoading" placeholder="请选择">
              <el-option v-for="(item,index) in classesList" :key="item.id"  :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="选择日期" prop="date">
              <el-date-picker
                  :clearable="false"
                  @change="dateChange"
                  v-model="form.date"
                  type="date"
                  placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="重复频率" prop="repeatType">
              <el-select v-model="form.repeatType" placeholder="请选择">
                <el-option label="不重复" :value="0"></el-option>
                <el-option :label="'每周(周'+selectedWeek+')'" :value="1"></el-option>
                <el-option :label="'每两周(周'+selectedWeek+')'" :value="2"></el-option>
                <el-option :label="'每月('+selectedDay+'日)'" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          </template>
        </template>
        <section style="text-align: center">
          <el-button size="small" @click="handleDialogClose">取消</el-button>
          <el-button size="small" type="primary" :loading="saveLoading" @click="handleConfirm"
            >确定</el-button
          >
        </section>
      </el-form>
    </el-dialog>
    <classesDetails v-if="classesDetailsVisible" :detailsVisible.sync="classesDetailsVisible" :handleType="handleClassesType" ref="detailsRef" />

  </div>
</template>
<script>
import ClassesDetails from "@/views/xtpz/classes/components/details.vue";
import {workingscheduleGetlist} from "@/api/pcmj/bcgl";
import {GetuserinfoById} from "@/api/login";
import {specialdaysCreate, specialdaysRemoveteampdata,specialdaysUpdate} from "@/api/pcmj/kqz";
import Details from "@/views/xtpz/classes/components/details.vue";
export default {
  components: {
    Details,
    ClassesDetails,
  },
  props: {
    attendanceGroupId:{
      type:String,
      default:""
    },
    rowData:{
      type: Object,
      default: ()=>{
        return {}
      },
    },
    dialogVisible:{
      type: Boolean,
      default: false,
    },
    formType: {
      type: String,
      default: "",
    },
    handleType: {
      type: String,
      default: "",
    },
  },
  computed: {
    headerTitle() {
      return this.formType == "1"
        ? "更改班次"
        : this.formType == "2"
        ? "修改其他打卡日期"
        : "添加其他打卡日期";
    },
  },
  data() {

    var validateDate = (rule, value, callback) => {
      if (value === null) {
        // 请选择班次
        callback(new Error('请选日期'));
      } else {
        callback();
      }
    };
    var validateWorkingScheduleId = (rule, value, callback) => {
      if (value === null) {
        // 请选择班次
        callback(new Error('请选择班次'));
      } else {
        callback();
      }
    };
    var validateName = (rule, value, callback) => {
      if (value === null) {
        // 请输入名称
        callback(new Error('请输入名称'));
      } else {
        callback();
      }
    };
    var validateRepeatType = (rule, value, callback) => {
      if (value === null) {
        // 请输入名称
        callback(new Error('请选择重复频率'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        name: [
          {validator: validateName, required: true, trigger: 'blur'},
          {max: 24, message: '长度最大 24 个字符', trigger: 'blur' }
        ],
        workingScheduleId: [
          {validator: validateWorkingScheduleId, required: true, trigger: 'blur'}
        ],
        date: [
          {validator: validateDate, required: true, trigger: 'blur'}
        ],
        repeatType: [
          {validator: validateRepeatType, required: true, trigger: 'blur'}
        ],

      },
      handleClassesType:'addSpecial',
      classesDetailsVisible:false,
      saveLoading:false,
      classesLoading:false,
      selectedYear:"",
      selectedMonth:"",
      selectedDay:"",
      selectedWeek:"",
      classesList:[],
      tmpdayList:[],
      dayEndList:[],
      form:{
        date:null,
        name:null,
        workingScheduleId:null,
        repeatType:0,
      }
    };
  },
  watch: {},
  methods: {
    dateChange(date){
      var weekday = ["日", "一", "二", "三", "四", "五", "六"];
      this.selectedYear=date.getFullYear()
      this.selectedMonth=date.getMonth()+1
      this.selectedMonth = this.selectedMonth < 10 ? "0" + this.selectedMonth : this.selectedMonth;

      this.selectedDay=date.getDate()
      this.selectedDay = this.selectedDay < 10 ? "0" + this.selectedDay : this.selectedDay;
      this.selectedWeek=weekday[date.getDay()]
      console.log('年：',this.selectedYear);
      console.log('月：',this.selectedMonth);
      console.log('日：',this.selectedDay);
      console.log('周：',this.selectedWeek);
    },
    workingscheduleGetlist(){
      this.classesLoading=true
      workingscheduleGetlist({
        pageNumber:1,
        pageSize:999,
        name:null
      }).then(res=>{
        if (res.code == 200) {
          this.classesList=res.data.values
          if (res.data.values.length&&this.handleType=="add"){
            this.form.workingScheduleId=res.data.values[0].id
          }
        }
      }).catch().finally(()=>{
        this.classesLoading=false
      })
    },
    handleDialogClose() {
      this.$parent.dialogVisible=false
    },
    setNewData(params){
      console.log(225, this.tmpdayList);
      this.tmpdayList=[];
      if (params.repeatType === 1) {

      } else if (params.repeatType === 2) {

      } else {

      }
    },
    specialdaysCreate(params){
      specialdaysCreate(params).then(res => {
        if (res.code == 200) {
          // 添加成功
          this.W.$tips("success", this.i18n.t('Add successfully!'));
          // 更新父页面表格
          this.$parent.getList()
          this.handleDialogClose()
        }
      }).catch().finally(()=>{
        this.saveLoading=false
      })
    },
    specialdaysUpdate(params){
      specialdaysUpdate(params).then(res=>{
        // 操作成功
        this.W.$tips("success", this.i18n.t('Operation successful'));
        // 更新父页面表格
        this.$parent.getList()
        this.handleDialogClose()
      }).catch().finally(()=>{
        this.saveLoading=false
      })
    },
    handleConfirmOld() {
    // handleConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid){
          this.saveLoading=true
          if (this.handleType=="add"){
            var params={
              name:this.form.name,
              attendanceGroupId:this.attendanceGroupId,
              workingScheduleId:this.form.workingScheduleId,
              date:this.selectedYear+"-"+this.selectedMonth+"-"+this.selectedDay,
              creatorId:JSON.parse(localStorage.getItem("userInfo")).userId
            }
            console.log('参数',params);
            if (params.repeatType > 0) {
              this.setNewData(params);
            }
          }else if(this.handleType=="specialDatesEdit"){
            // 修改特殊日期表格
            var params=JSON.parse(JSON.stringify(this.rowData))
            params.accountInfo=null
            params.workingSchedule=null
            params.name=this.form.name
            params.workingScheduleId=this.form.workingScheduleId
            this.specialdaysUpdate(params)
          }else if (this.handleType="selectShift"){
            // 固定班制表格选择班次
            this.$emit('childEvent', this.form.workingScheduleId);
            this.handleDialogClose()
          }
        }else{
          return false
        }
      })
    },
    async addSpecialDays(inputDate,RepeatType)
    {
      const timestamp = Date.now();
      const nowDate = new Date(timestamp);
      const year = nowDate.getFullYear();
      const month = (nowDate.getMonth() + 1).toString().padStart(2, '0');
      const day = nowDate.getDate().toString().padStart(2, '0');
      const hours = nowDate.getHours().toString().padStart(2, '0');
      const minutes = nowDate.getMinutes().toString().padStart(2, '0');
      const seconds = nowDate.getSeconds().toString().padStart(2, '0');

      const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

       var self = this
       var userId = JSON.parse(localStorage.getItem("userInfo")).userId
       var userInfo;
       var res = await GetuserinfoById(userId)
        if (res.code == 200) {
            console.log(312, res );
            userInfo=res.data

        }
        function createSpecialday(date)
        {
              var workingSchedule =self.classesList.find(x=>x.id==self.form.workingScheduleId)
              console.log(123, workingSchedule);
              var reuslt = {
                name:self.form.name,
                attendanceGroupId:self.attendanceGroupId,
                workingScheduleId:self.form.workingScheduleId,
                workingSchedule:workingSchedule,
                date:date.getFullYear()+"-"+(date.getMonth() + 1).toString().padStart(2, '0')+"-"+date.getDate().toString().padStart(2, '0'),
                repeatType:self.form.repeatType,
                accountInfo:userInfo,
                createTime:formattedDateTime,
                creatorId:  userId
              }
              return reuslt
        }
        var results= []
        if(RepeatType==0)
        {
           var item = createSpecialday(inputDate)
           results.push(item)
        }
        else
        {
          var t0= inputDate
          var t1 = new Date(t0.getFullYear()+1, t0.getMonth(), t0.getDate())
          var week = inputDate.getDay();
          console.log(17, week);
          // return;
          for(var date=new Date(t0.getTime());date<=t1;date = new Date(date.getTime() + 24 * 60 * 60 * 1000) )
          {
              if (RepeatType === 1) {
                  if (date.getDay() == inputDate.getDay()) {
                      //console.log(23, date.getDay(), date.toLocaleString());
                      var item = createSpecialday(date)
                      results.push(item)
                  }
              } else if (RepeatType === 2) {
                  // Math.floor((inputDate - date) / (1000 * 60 * 60 * 24));
                  if (date.getDay() == inputDate.getDay() && (Math.floor((date - inputDate) / (1000 * 60 * 60 * 24)) /7) %2 == 0) {
                      //console.log(33, date.getDay(), date.toLocaleString());
                      var item = createSpecialday(date)
                      results.push(item)
                  }
              } else {
                  if (date.getDate() == inputDate.getDate()) {
                      //console.log(43, date.getDay(), date.toLocaleString());
                      var item = createSpecialday(date)
                      results.push(item)
                  }
              }
              // console.log(date.toLocaleString())
          }
        }
        console.log("oooooo",results)
        results.forEach(x=>
        {
          this.rowData.values.push(x)
        });

        // this.rowData.values = [...this.rowData.values, ...results]
        // this.$set(this.rowData, 'values', [...this.rowData.values, ...results])
        this.$nextTick(() => {
          this.$parent.getList()
        })
        console.log("xxxx",this.rowData.values)

    },
    handleConfirm() {
    // handleConNewfirm() {
      this.$refs.form.validate((valid) => {
        if (valid){
          this.saveLoading=true
          if (this.handleType=="add"){
              // {
              //   "attendanceGroupId": "635bb688-995b-4e5c-af69-207941205728",
              //   "attendanceGroup": null,
              //   "name": "423423",
              //   "workingScheduleId": "8f40c6a8-9cf8-499e-8a92-ce0d727a82cd",
              //   "date": "2025-04-26",
              //   "creatorId": "f9fe8c2e-efdc-4263-8e35-0a4365a07780",
              // },
            /* var params={
              name:this.form.name,
              attendanceGroupId:this.attendanceGroupId,
              workingScheduleId:this.form.workingScheduleId,
              date:this.selectedYear+"-"+this.selectedMonth+"-"+this.selectedDay,
              repeatType:this.form.repeatType,
              creatorId:JSON.parse(localStorage.getItem("userInfo")).userId
            }
            console.log('参数',params);
            this.specialdaysCreate(params) */
            // console.log('000', this.selectedYear, this.selectedMonth)
            this.addSpecialDays(new Date(this.selectedYear,parseInt(this.selectedMonth)-1,this.selectedDay),this.form.repeatType)
            // this.$parent.getList()
            this.handleDialogClose()
            // GetuserinfoById
          }else if(this.handleType=="specialDatesEdit"){
            // 修改特殊日期表格
            //this.rowData.accountInfo=null
            //this.rowData.workingSchedule=null
            this.rowData.name=this.form.name
            //this.rowData.workingScheduleId=this.form.workingScheduleId
            console.log('修改完',this.rowData);
            // 操作成功
            this.W.$tips("success", this.i18n.t('Operation successful'));
            // 更新父页面表格
            //this.$parent.getList()
            this.handleDialogClose()
            console.log(337);
          }else if (this.handleType="selectShift"){
            // 固定班制表格选择班次
            this.$emit('childEvent', this.form.workingScheduleId);
            this.handleDialogClose()
          }
        }else{
          return false
        }
      })


    },
    open() {
      this.dialogVisible = true;
    },
    addClasses() {
      this.classesDetailsVisible=true
      this.$refs.detailsRef.open();
    },
  },
  mounted(){
    // 特殊日期设置修改弹窗赋值
    if (this.handleType=='specialDatesEdit'){
      /* console.log(11, this.rowData);
      var params=JSON.parse(JSON.stringify(this.rowData))
      console.log('传过来的参数',params);
      this.form.name=params.name
      this.form.workingScheduleId=params.workingScheduleId */
      this.form.name=this.rowData.name
      this.form.workingScheduleId=this.rowData.workingScheduleId
    }
    this.workingscheduleGetlist()
  }
};
</script>
<style scoped lang="scss">
::v-deep.form-container {
  .el-form-item {
    display: inline-flex;
    .el-form-item__label {
      width: 105px !important;
    }
  }
}

::v-deep #addTips {
  position: relative;
}
::v-deep #addTips .newShift {
  position: absolute;
  right: 25px;
  z-index: 100;
}
::v-deep #addTips .el-row .el-form-item__label {
  text-align: right;
  width: 100px !important;
}
::v-deep #addTips .el-row .el-input__inner,
::v-deep #addTips .el-row .el-select {
  width: 205px !important;
}
::v-deep #addTips .el-row .el-form-item__content {
  display: inline-block;
}
</style>
